package com.haiyan.role.controller;

import com.alibaba.fastjson.JSONObject;
import com.haiyan.base.BaseController;
import com.haiyan.role.service.RoleService;
import com.haiyan.role.service.impl.RoleServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import java.io.BufferedReader;
import java.io.IOException;

/**
 * 这里要做的事情：先判断请求到的方法是什么
 * 调用servicr的方法(拿到前端的值，塞进service的方法中，返回响应)
 */

@WebServlet(name = "zhyRolePostController", urlPatterns = "/zhyRole/post.do")
public class RolePostController extends BaseController {

    private RoleService roleService = new RoleServiceImpl();

    @Override
    public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        // 请求拿到URl的method后的值
        BufferedReader reader = request.getReader();

        String s = "";
        while (reader != null) {
            String rs = reader.readLine();
            s = s + rs;
            if (rs.equals("}")) {
                break;
            }
        }

        JSONObject jsonObject = JSONObject.parseObject(s);
        String method = jsonObject.getString("method");
        String name = jsonObject.getString("name");
        // 当前端选择id时就删除对应的数据
        Integer id = jsonObject.getInteger("id");


        // 拿到method=什么就做什么事情
        if ("addRole".equals(method)) {
            addRole(name,response);
        } else if ("deleteRole".equals(method)) {
            deleteRole(id,response);
        } else if ("updateRole".equals(method)) {
            updateRole(id,name,response);
        }
    }

    // 做的事情
    public void addRole(String name,ServletResponse response) throws IOException {

        // 调用service方法，将值赋给他
        int i = roleService.addRole(name);

        // 响应
        // response
        // check:判断要进那个方法 if的还是else if的
        // i:（增删改时：代表影响的行数），要给前端的数据（方法的类型）
        // 500：当check为false时，要进入else if的哪一个方法
        boolean check = i > 0;
        printData(check, i, 500, response);
    }

    public void deleteRole(Integer id,ServletResponse response) throws IOException {
        int i = roleService.deleteRoleById(id);

        boolean check = i > 0;
        printData(check, i, 500, response);
    }

    public void updateRole(Integer id,String name,ServletResponse response) throws IOException {

        int i = roleService.updateRoleNameById(id, name);

        boolean check = i > 0;
        printData(check, i, 500, response);
    }
}
